package com.example.googlemapdrawroutelast;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.view.View;
import android.widget.Toast;

public class GetRouteByIdTask2 extends AsyncTask<Void, Void, Boolean> {

	private View view;
	private Context context;
	private ArrayList<RouteInfo> routes = new ArrayList<RouteInfo>();
	private ApplicationData appData;

	public GetRouteByIdTask2(View view, Context context,ApplicationData appData) {
		super();
		this.view = view;
		this.context = context;
		this.appData = appData;
	}
	
	public GetRouteByIdTask2() {
		super();
	
	}
	@Override
	protected Boolean doInBackground(Void... params) {
		try {
			String strUrl = "http://" + UrlClass.getUrl() + "/v1/routes";
			URL url = new URL(strUrl);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setRequestMethod("GET");
			connection.setDoOutput(true);

			InputStream iStream = connection.getInputStream();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(iStream));

			StringBuffer sb = new StringBuffer();
			String line = "";

			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}

			reader.close();
			iStream.close();

			String jsonResponseString = sb.toString();
			JSONObject jsonResponse = new JSONObject(jsonResponseString);
			JSONArray routesArray = jsonResponse.getJSONArray("routes");

			routes.clear();

			for (int i = 0; i < routesArray.length(); i++) {
				JSONObject route = (JSONObject) routesArray.get(i);
				routes.add(new RouteInfo(
						 route.getInt("id_route"),
						 route.getString("name_route"),
						 route.getString("description"),
						 null,
						 null,
						 route.getInt("id_user")));
			}
			

		} catch (Exception e) {
			Toast.makeText(context, e.getMessage(),
					Toast.LENGTH_SHORT).show();
		}
		return null;
	}

	@Override
	protected void onPostExecute(Boolean result) {
		super.onPostExecute(result);
		createNewListOfRouteActivity(view);
	}

	private void createNewListOfRouteActivity(View v) {

		Intent intent = new Intent(v.getContext(),
				ListOfRoutesActivity.class);
		intent.putParcelableArrayListExtra("routes", routes);
		
		int iduseros  = appData.getIdUser();
		intent.putExtra("idUser", iduseros);
		//startActivityForResult(intent, 0);
		context.startActivity(intent);
		
	}

}


